package com.it.xyx.demo.config;

import com.it.xyx.demo.entity.User;
import com.it.xyx.demo.service.impl.UserServiceImpl;
import jakarta.annotation.Resource;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @Classname MyShiroRealm
 * @Description TODO
 * @Date 2024/8/23 23:04
 * @Created by 潜伏Sir
 */
public class MyShiroRealm extends AuthorizingRealm {

    private Logger log = LoggerFactory.getLogger(MyShiroRealm.class);

    @Resource
    UserServiceImpl userService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("===================权限验证==================");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        // 获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        //获得权限列表
        authorizationInfo.addStringPermission(user.getPers());
        return authorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        User currentUser = userService.lambdaQuery().eq(User::getUsername, token.getUsername()).one();
        if (null == currentUser) {
            throw new AuthenticationException("账户不存在");
        }

        if (!currentUser.getPassword().equals(new String(token.getPassword()))) {
            throw new IncorrectCredentialsException("账户密码不正确");
        }


        Subject subject = SecurityUtils.getSubject();

        User user = new User();

        user.setUsername(currentUser.getUsername());
        user.setPassword(currentUser.getPassword());


        log.info("======已授权" + user.toString() + "====");

        return new SimpleAuthenticationInfo(user, user.getPassword(), user.getUsername());
    }

}
